﻿using System;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using Windows.Data.Html;
using Windows.Data.Xml.Dom;
using Windows.UI.Notifications;
using Windows.UI.Xaml.Controls;

namespace MetroDictionary
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage
    {
        /*
         * TODO:
         * METRO integration (search contract, live tile (with random word)) - DONE!
         * Download dictionaries
         * Speedup loading (split words and translations)
         * Keyboard navigation
         * 
         * Publish?? http://msdn.microsoft.com/en-us/library/windows/apps/hh868181.aspx
         * http://msdn.microsoft.com/en-us/library/windows/apps/hh694083.aspx
         * 
         */

        private readonly Random _rnd = new Random();
        private readonly MainPageViewModel _viewModel;

        public MainPage()
        {
            InitializeComponent();
            DataContext = _viewModel = new MainPageViewModel();
            _viewModel.PropertyChanged += ViewModelPropertyChanged;

            SetupLiveTile();
        }

        private async void SetupLiveTile()
        {
            await _viewModel.WaitForLoadingAsync();
            var tileUpdater = TileUpdateManager.CreateTileUpdaterForApplication();

            tileUpdater.EnableNotificationQueue(true);

            for (var i = 0; i < 5; i++)
            {
                var tileXml = GetLiveTileWithRandomWord();
                tileUpdater.Update(new TileNotification(tileXml));
            }
        }

        private XmlDocument GetLiveTileWithRandomWord()
        {
            var count = _viewModel.Words.Count();
            var wordToShow = _viewModel.Words.Skip(_rnd.Next(count - 1)).First();
            var translation = HtmlUtilities.ConvertToText(_viewModel.GetTranslation(wordToShow));

            // Standard tile
            var tileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquareText02);
            var tileTextAttributes = tileXml.GetElementsByTagName("text");
            tileTextAttributes[0].AppendChild(tileXml.CreateTextNode(wordToShow));
            tileTextAttributes[1].AppendChild(tileXml.CreateTextNode(translation));

            // Add wide tile to the payload
            var wideTileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWideText09);
            var wideTileTextAttributes = wideTileXml.GetElementsByTagName("text");
            wideTileTextAttributes[0].AppendChild(wideTileXml.CreateTextNode(wordToShow));
            wideTileTextAttributes[1].AppendChild(wideTileXml.CreateTextNode(translation));
            var node = tileXml.ImportNode(wideTileXml.GetElementsByTagName("binding").Item(0), true);
            tileXml.GetElementsByTagName("visual").Item(0).AppendChild(node);
            return tileXml;
        }

        private void ViewModelPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "SelectedWord")
            {
                wordList.ScrollIntoView(_viewModel.SelectedWord);
            }
        }

        private void SearchTextBoxTextChanged(object sender, TextChangedEventArgs e)
        {
            // There is no UpdateSourceTrigger = PropertyChanged :(
            _viewModel.SearchText = searchTextBox.Text;
        }

        public async Task DisplaySearchResults(string query)
        {
            await _viewModel.WaitForLoadingAsync();
            _viewModel.SearchText = searchTextBox.Text = query;
        }
    }
}